/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainForm.java
 *
 * Created on Apr 13, 2014, 12:50:48 PM
 */
package com.mcet.outliers;

import com.mcet.Table;
import com.mcet.outliers.data.MedicalMap;
import com.mcet.outliers.database.DbManager;
import com.mcet.outliers.log.Log;
import java.util.ArrayList;
import java.util.HashSet;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListModel;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.application.Action;
import org.jdesktop.application.Task;

/**
 *
 * @author dell
 */
public class MainForm extends javax.swing.JFrame {

    private Table outliers;
    private int index;
    private String[] outlierColumns;
    private String tableName;

    /** Creates new form MainForm */
    public MainForm() {
        initComponents();
        
        jLabel3.setVisible(false);
        //jTable1.setVisible(false);
        jScrollPane2.setVisible(false);
        jButton3.setVisible(false);
        jList2.setVisible(false);
        jButton4.setVisible(false);
        jPanel2.setVisible(false);
        jLabel6.setText("Connected to database : "+DbManager.getInstance().getDbpath());
        
    }

    MainForm(String tableName, String[] outlierColumns) {
        this.tableName = tableName;
        this.outlierColumns = outlierColumns;
          initComponents();
        jLabel3.setVisible(false);
        //jTable1.setVisible(false);
        jScrollPane2.setVisible(false);
        jButton3.setVisible(false);
        jList2.setVisible(false);
        jButton4.setVisible(false);
        jPanel2.setVisible(false);
        jLabel6.setText("Connected to database : "+DbManager.getInstance().getDbpath());
        jLabel2.setText("Selected table "+tableName);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N
        setResizable(false);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.mcet.outlier.class).getContext().getResourceMap(MainForm.class);
        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setForeground(resourceMap.getColor("jLabel1.foreground")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(com.mcet.outlier.class).getContext().getActionMap(MainForm.class, this);
        jButton2.setAction(actionMap.get("onFindOutlilerClicked")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
        jLabel3.setForeground(resourceMap.getColor("jLabel3.foreground")); // NOI18N
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable1);

        jButton3.setAutoscrolls(true);
        jButton3.setLabel(resourceMap.getString("Delete.label")); // NOI18N
        jButton3.setName("Delete"); // NOI18N
        jButton3.setRolloverEnabled(false);
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });

        jButton4.setAction(actionMap.get("detectDataClicked")); // NOI18N
        jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N
        jButton4.setName("jButton4"); // NOI18N

        jPanel2.setName("jPanel2"); // NOI18N

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        jList2.setName("jList2"); // NOI18N
        jScrollPane3.setViewportView(jList2);

        jLabel4.setFont(resourceMap.getFont("jLabel4.font")); // NOI18N
        jLabel4.setForeground(resourceMap.getColor("jLabel4.foreground")); // NOI18N
        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(53, 53, 53)
                        .addComponent(jLabel4)))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(27, Short.MAX_VALUE))
        );

        jLabel5.setIcon(resourceMap.getIcon("jLabel5.icon")); // NOI18N
        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jLabel6.setFont(resourceMap.getFont("jLabel6.font")); // NOI18N
        jLabel6.setForeground(resourceMap.getColor("jLabel6.foreground")); // NOI18N
        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setForeground(resourceMap.getColor("jLabel2.foreground")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addComponent(jLabel5)
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(jLabel6))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 980, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(11, 11, 11)
                                        .addComponent(jLabel3))
                                    .addComponent(jButton2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 383, Short.MAX_VALUE)
                                .addComponent(jButton4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButton3)
                                .addGap(14, 14, 14)))))
                .addContainerGap(35, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(37, 37, 37)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel2)
                        .addGap(20, 20, 20)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addComponent(jButton2)
                        .addGap(28, 28, 28)
                        .addComponent(jLabel3))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(19, 19, 19)
                                .addComponent(jButton4)
                                .addGap(57, 57, 57))
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jButton3)))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked


        int selection = JOptionPane.showConfirmDialog(null, "Are you sure you want to Delete", "Delete", JOptionPane.OK_OPTION, JOptionPane.CANCEL_OPTION);

        Log.debug("selection ::: " + selection);

        if (selection == JOptionPane.OK_OPTION) {
            deleteOutlier();

        }
    }//GEN-LAST:event_jButton3MouseClicked

    private void deleteOutlier() {
         ArrayList<String> delData = outliers.getOutlierData().get(index);
         ArrayList<String> columns = outliers.getColumns();
         String whereClause = "";
         for (int i = 0; i < delData.size(); i++) {
             if(i==0){
             whereClause += columns.get(i) + " = '" + delData.get(i)+"'";
                     }else {
                 whereClause += " and  "+columns.get(i) + " = '" + delData.get(i)+"'";

             }
         }
         DbManager.getInstance().deleteOutlier(whereClause, tableName);
         outliers.deleteData(index);
         showTable();
         jButton3.setVisible(false);
     
    }
    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked

        index = jTable1.getSelectedRow();
        Log.debug("Index = " + index);
        jButton3.setVisible(true);
        jButton4.setVisible(true);
    }//GEN-LAST:event_jTable1MouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainForm().setVisible(true);
            }
        });
    }

    @Action
    public void populateTables() {
        // Add tables to list
      /*  DbManager db = DbManager.getInstance();
        String dbName = db.getDbpath();//databaseComboList.getSelectedItem().toString();
        ArrayList<String> tables = db.getTables(dbName);
        // ListModel model = jList1.getModel();
        DefaultListModel model = new DefaultListModel();
        for (String table : tables) {
            model.addElement(table);
        }
        jList1.setModel(model);*/


    }

    @Action
    public Task onFindOutlilerClicked() {
        return new OnFindOutlilerClickedTask(org.jdesktop.application.Application.getInstance(com.mcet.outlier.class));
    }

    private class OnFindOutlilerClickedTask extends org.jdesktop.application.Task<Object, Void> {

        OnFindOutlilerClickedTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to OnFindOutlilerClickedTask fields, here.
            super(app);
            jLabel3.setVisible(true);
            jLabel3.setText("Finding Outliers...");
        }

        @Override
        protected Object doInBackground() {
            // Your Task's code here.  This method runs
            // on a background thread, so don't reference
            // the Swing GUI from here.
            MedicalMap map = MedicalMap.getInstance();
            DbManager db = DbManager.getInstance();
            /*String outlierColumns[] = {"Secondary_Group", "Diagnosis", "Search_Terms", "Full_diagnosis",
                "FSN"
            };*/
            
          // outliers = db.detectOutlierUsingSingleThread(map, tableName, outlierColumns); // Single Thread
          outliers = db.detectOutlier(map, tableName, outlierColumns); // MultiThread 

            return null;  // return your result
        }

        @Override
        protected void succeeded(Object result) {
            // Runs on the EDT.  Update the GUI based on
            // the result computed by doInBackground().
            Log.debug("No of Outliers : " + outliers.getOutlierData().size());


            showTable();
        }
    }
    private DefaultTableModel dataModel;

    private void showTable() {
        jLabel3.setText("Found " + outliers.getOutlierData().size() + " Outliers...");
       /* String outlierColumns[] = {"Secondary_Group", "Diagnosis", "Search_Terms", "Full_diagnosis",
            "FSN"
        };*/
        dataModel = new DefaultTableModel();
        jTable1.setModel(dataModel);
        dataModel.setColumnIdentifiers(outlierColumns);

        for (int i = 0; i < outliers.getOutlierData().size(); i++) {
            ArrayList<String> outlier = outliers.getOutlierData().get(i);
            String[] row = new String[outlier.size()];
            for (int j = 0; j < outlier.size(); j++) {
                for (int k = 0; k < outlierColumns.length; k++) {
                    if (outliers.getColumnName(j).equals(outlierColumns[k])) {
                        row[k] = outlier.get(j);
                        
                    }
                }
            }
            dataModel.addRow(row);
        }
        jScrollPane2.setVisible(true);
    }

    @Action
    public Task detectDataClicked() {
        return new DetectDataClickedTask(org.jdesktop.application.Application.getInstance(com.mcet.outlier.class));
    }

    private class DetectDataClickedTask extends org.jdesktop.application.Task<Object, Void> {

        DetectDataClickedTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to DetectDataClickedTask fields, here.
            super(app);
        }

        @Override
        protected Object doInBackground() {

            return outliers.getPossibleValue(index);
        }

        @Override
        protected void succeeded(Object result) {
            ArrayList<String> data = (ArrayList<String>) result;
            for (String pD : data) {
                Log.debug("Possible Value ::: " + pD);

            }
            jPanel2.setVisible(true);
            jList2.setVisible(true);
             HashSet<String> set = new HashSet<String>();
             for (String value : data) {
                 set.add(value);
             }
            DefaultListModel model = new DefaultListModel();
            for (String value : set) {
                if(!value.equals("No Key")){
                    model.addElement(value);
                }
            }
            jList2.setModel(model);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JList jList2;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
